package org.example.mallsystem1104.service;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.mallsystem1104.constants.Constants;
import org.example.mallsystem1104.entity.MyFile;
import org.example.mallsystem1104.exception.ServiceException;
import org.example.mallsystem1104.mapper.FileMapper;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@Service
public class FileService extends ServiceImpl<FileMapper, MyFile> {


    public void download(String fileName, HttpServletResponse response) {
        File file=new File(Constants.fileFolderPath+fileName);
        if (!file.exists()){
            throw new ServiceException(Constants.CODE_500,"文件不存在");
        }
        try {
            ServletOutputStream os=response.getOutputStream();
            response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
            response.setContentType("application/octet-stream");
            os.write(FileUtil.readBytes(file));
            os.flush();
            os.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
